package cn.wolfcode.shop.util;

import lombok.Getter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class CookieUtils {
    private static final String DOMAIN = "localhost";
    private static final String PATH = "/";
    private static final Integer TIME = 30 * 60;
    public static final String USERTOKEN_NAME = "userToken";

    // 将数据添加进cookie中
    public static void addInCookie(HttpServletResponse response, String cookieName, String cookieVal) {
        Cookie cookie = new Cookie(cookieName, cookieVal);
        cookie.setMaxAge(TIME);
        cookie.setDomain(DOMAIN);
        cookie.setPath(PATH);
        //共享cookie
        response.addCookie(cookie);
    }

    // 获取 cookie 的值
    public static String getCookieValue(HttpServletRequest request, String userToken) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(userToken)) {
                // 应该还缺一个条件，这个 cookie 中的 token 必须是当前用户的token才行
                // 思路：getValue() 以后，在根据当前用户去Redis中查询用户对应的token来进行比较，相同的才可以放行
                return cookie.getValue();
            }
        }
        return null;
    }
}
